package com.future.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Header;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/file")
public class FileController {

    //文件上传并且获取时间
    @RequestMapping("/uploadAndTime")
    @ResponseBody
    public String uploadAndTime(@RequestParam("file") MultipartFile filex) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tMD2SS1nzgLxYwxggVJ";
        String accessKeySecret = "ujQ3Ls8rcvEnLB9WNzVv75DryEdBhT";
        String uploadFileName = filex.getOriginalFilename();

        int miao = 0;
        //获取文件路径
        String fileName = uploadFileName;
        String bucketName = "jianglin-bucket";
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成上传文件名
        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
        String objectName = sdf.format(new Date()) + "/" + finalFileName;

//这个路径是删除的路径
        System.out.println(objectName);

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try {
            ossClient.putObject(bucketName, objectName, filex.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + 999999999 * 1000000000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        ossClient.shutdown();
        //获取mp3文件时间
        try {
            URL urlfile = new URL(url.toString());
            URLConnection con = urlfile.openConnection();
            int b = con.getContentLength();// 得到音乐文件的总长度
            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
            Bitstream bt = new Bitstream(bis);
            Header h = bt.readFrame();
            int time = (int) h.total_ms(b);
            miao = time / 1000;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BitstreamException e) {
            e.printStackTrace();
        }
        System.out.println(url.toString());
        int mm = (miao % 3600) / 60;
        int ss = (miao % 3600) % 60;
        System.out.println((mm < 10 ? ("0" + mm) : mm) + ":" + (ss < 10 ? ("0" + ss) : ss));

        return "list";
    }


    //文件上传
    @RequestMapping("/upload")
    @ResponseBody
    public String Upload(@RequestParam("file") MultipartFile filex) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tMD2SS1nzgLxYwxggVJ";
        String accessKeySecret = "ujQ3Ls8rcvEnLB9WNzVv75DryEdBhT";
        String uploadFileName = filex.getOriginalFilename();
        //获取文件路径
        String fileName = uploadFileName;
        String bucketName = "jianglin-bucket";
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成上传文件名
        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
        String objectName = sdf.format(new Date()) + "/" + finalFileName;
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try {
            ossClient.putObject(bucketName, objectName, filex.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 设置URL过期时间。
        Date expiration = new Date(System.currentTimeMillis() + 999999999 * 1000000000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        ossClient.shutdown();
        System.out.println(url.toString());
        return "list";
    }


    //文件删除
    @RequestMapping("/delete")
    @ResponseBody
    public boolean delete(String filePath) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tMD2SS1nzgLxYwxggVJ";
        String accessKeySecret = "ujQ3Ls8rcvEnLB9WNzVv75DryEdBhT";


        //获取文件路径
        //文件路径需要截取
        filePath = "20210609/1623244282415334.png";
        String bucketName = "jianglin-bucket";


        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        boolean exist = ossClient.doesObjectExist(bucketName, filePath);

        if (!exist) {
            return false;
        }

        ossClient.deleteObject(bucketName, filePath);
        ossClient.shutdown();
        return true;
    }


    //文件下载
    @RequestMapping("/download")
    @ResponseBody
    public void download(HttpServletResponse response, String filePath) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tMD2SS1nzgLxYwxggVJ";
        String accessKeySecret = "ujQ3Ls8rcvEnLB9WNzVv75DryEdBhT";
        //获取文件路径
        //文件路径需要截取
        filePath = "20210601/1622552464710248.jpg";
        String bucketName = "jianglin-bucket";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, filePath);
        // 读去Object内容  返回
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        try {
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filePath, "utf-8"));
            //BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\\a.txt")));
            byte[] car = new byte[1024];
            int L = 0;
            while ((L = in.read(car)) != -1) {
                out.write(car, 0, L);
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        ossClient.shutdown();
    }


}




